package com.rongzhe.house.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.rongzhe.house.common.SpringUtil;
import com.rongzhe.house.common.cache.CommonCacheUtil;
import com.rongzhe.house.common.constants.Constants;
import com.rongzhe.house.common.constants.Parameters;
import com.rongzhe.house.common.resp.ApiResult;
import com.rongzhe.house.user.entity.UserElement;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by HeGang 11:29 2018/5/22.
 */
public class TokenInterceptor implements HandlerInterceptor {


    private Parameters parameters = SpringUtil.getBean(Parameters.class);

    private AntPathMatcher matcher = new AntPathMatcher();

    private CommonCacheUtil commonCacheUtil = SpringUtil.getBean(CommonCacheUtil.class);


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {

        String token = request.getHeader(Constants.REQUEST_TOKEN_KEY);

        String uri = request.getRequestURI().toString();
        boolean isNoneCheck = isNoneSecurity(uri.substring(4, uri.length()));

        if (isNoneCheck || "OPTIONS".equals(request.getMethod())) {

            return true;
        }


        boolean tokenError;

        if (token != null && !token.trim().isEmpty()) {
            UserElement ue = commonCacheUtil.getUserByToken(token);
            if (ue != null && ue instanceof UserElement) {


                return true;
            } else {
                tokenError = true;
            }
        } else {
            tokenError = true;
        }

        if (tokenError) {
            ApiResult apiResult = new ApiResult();

            apiResult.setCode(401);
            apiResult.setMessage("请您先登录");

            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().write(JSON.toJSONString(apiResult));

            return false;
        }


        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }


    /**
     * 校验是否是无需权限的url
     *
     * @param uri
     * @return
     */
    private boolean isNoneSecurity(String uri) {
        boolean result = false;
        if (this.parameters.getNoneSecurityPath() != null) {
            for (String pattern : this.parameters.getNoneSecurityPath()) {
                if (matcher.match(pattern, uri)) {
                    result = true;
                    break;
                }
            }
        }

        return result;
    }
}
